import EXIF from 'exif-js'
/**
 * DataUrl转为File
 * @param {String} dataUrl - dataUrl地址
 * @param {String} fileName - file文件名
 */
export function dataURLtoFile(dataUrl, fileName) {
	let arr = dataUrl.split(',');
	let mime = arr[0].match(/:(.*?);/)[1];
	let bstr = atob(arr[1]);
	let n = bstr.length;
	let u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], fileName, {
		type: mime
	});
}

/**
 * blob转成base64
 * @param {*} blob 
 * @returns 
 */
export function blobToDataUrl(blob) {
	return new Promise(function(resolve) {
		const fr = new FileReader();
		fr.onload = function(e) {
			resolve(e.target.result)
		}
		fr.readAsDataURL(blob)
	})
}

/**
 * file类型转成blob
 * @param {*} file 
 * @returns 
 */
export function fileToBlob(file){
    return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        reader.onload   = (e) => {
            let blob;
            if(typeof e.target.result === 'object'){
                blob = new Blob([e.target.result]);
            }else {
                blob = e.target.result;
            }

            resolve(blob);
        }
        reader.readAsArrayBuffer(file);
    })    
}

export function compressImg(file, baseSize, needRotate, defaultOri) {

	return new Promise(function(resolve, reject) {
		let orientation = null
		if (file) {

            // 某些设备拍摄的照片exifdata与iptcdata会丢失，会执行异常
            // 补齐exifdata与iptcdata，保证extif能正常解析
            file.exifdata = file.exifdata || {};
            file.iptcdata = file.iptcdata || {};

            try {
                EXIF.getData(file, function() {
                    EXIF.getAllTags(this);
                    orientation = EXIF.getTag(this, 'Orientation');
                    orientation = [1,2,3,4,5,6,7,8].indexOf(Number(orientation)) > -1? orientation: defaultOri;
                    // 通过FormData构造函数创建一个空对象
                    let reader = new FileReader();
                    // 将读取到的文件编码成DataURL
                    reader.readAsDataURL(file);
                    // 压缩图片
                    reader.onload = function(ev) {
                        // 读取图片来获得上传图片的宽高
                        let img = new Image();
                        img.src = ev.target.result;
                        img.onload = function(e) {
                            // 将图片绘制到canvas画布上进行压缩
                            let imgWidth = img.width;
                            let imgHeight = img.height;
    
                            const baseWidth = 750
                            const baseHeight = 1200
    
                            // 控制上传图片的宽高
                            if (imgWidth > imgHeight && imgWidth > baseWidth) {
                                imgWidth = baseWidth;
                                imgHeight = Math.ceil(baseWidth * imgHeight / img.width);
                            } else if (imgWidth < imgHeight && imgHeight > baseHeight) {
                                imgWidth = Math.ceil(baseHeight * img.width / img.height);
                                imgHeight = baseHeight;
                            }
    
                            // 按比例缩放后图片宽高;
                            let targetwidth = imgWidth;
                            let targetHeight = imgHeight;
    
                            let canvas = document.createElement("canvas");
                            let ctx = canvas.getContext("2d");
                            // 缩放后高度仍然大于最大高度继续按比例缩小
                            canvas.width = targetwidth; //canvas的宽=图片的宽
                            canvas.height = targetHeight; //canvas的高=图片的高

                            if (needRotate && orientation && orientation != 1) {
                                switch (orientation) {
                                    case 6: // 旋转90度
                                        canvas.width = imgHeight;
                                        canvas.height = imgWidth;
                                        ctx.rotate(Math.PI / 2);
                                        // (0,-imgHeight) 从旋转原理图那里获得的起始点
                                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                                        ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
                                        break;
                                    case 3: // 旋转180度
                                        ctx.rotate(Math.PI);
                                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                                        ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth,
                                            imgHeight);
                                        break;
                                    case 8: // 旋转-90度
                                        canvas.width = imgHeight;
                                        canvas.height = imgWidth;
                                        ctx.rotate(3 * Math.PI / 2);
                                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                                        ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                                        break;
                                }
                                ctx.clearRect(0, 0, canvas.width, canvas.height);
                                ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                            } else {
                                ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
                            }
                            
                            // 开启压缩的基准文件大小50kb
                            const baseFileSize = baseSize;
                            // 如果图片小于基准文件大小，不进行压缩，并返回二进制流
                            if (file.size <= baseFileSize) {
                                canvas.toBlob(function(blob) {
                                    console.info(`文件压缩后大小${blob.size}`)
                                    resolve(blob)
                                }, file.type, 1);
                                // fileToBlob(file).then(blob => {
                                //     resolve(blob);
                                // })
                                // resolve(file)
                            }
                            // 如果图片大于基准文件大小，进行压缩，并返回二进制流
                            else {
                                // 压缩文件大小比例
                                canvas.toBlob(function(blob) {
                                    console.info(`文件压缩后大小${blob.size}`)
                                    resolve(blob)
                                }, file.type, 0.6);
                            }
                        };
                    };
    
                });
            } catch (error) {
                // 如果执行压缩异常，忽略压缩，直接返回原文件的blob
                fileToBlob(file).then(blob => {
                    resolve(blob);
                })
            }            
		}

	})

}